package org.sasha.roulette.actionbar;

import javax.inject.Inject;

import org.sasha.roulette.SessionContext;
import org.sasha.roulette.data.DBHelper;
import org.sasha.roulette.event.SessionChangedEvent;

import com.github.peholmst.mvp4vaadin.Presenter;
import com.google.common.eventbus.EventBus;
import com.vaadin.data.util.sqlcontainer.RowId;

@SuppressWarnings("serial")
public class ActionBarPresenter extends Presenter<ActionBarView> {

    private DBHelper dbHelper;
    
    private EventBus eventBus;
    
    @Inject
    public ActionBarPresenter(final EventBus eventBus, final DBHelper dbHelper) {
        this.eventBus = eventBus;
        this.dbHelper = dbHelper;
    }
    
    public void initializeNewSession() {
        int sessionId = dbHelper.createNewSession();
        SessionContext.get().setSessionId(sessionId);
        getView().setSessionList(dbHelper.getSessionContainer());
        eventBus.post(new SessionChangedEvent(sessionId));
    }
    
    @Override
    public void setView(ActionBarView view) {
        super.setView(view);
        view.setSessionList(dbHelper.getSessionContainer());
    }

    public Object getDefaultSessionId() {
        return new RowId(new Object[]{dbHelper.getLatestSessionID()});
    }

    public void changeCurrentSession(Object value) {
        if (value instanceof RowId) {
            final RowId id = (RowId)value;
            int sessionId = (Integer)id.getId()[0];
            SessionContext.get().setSessionId(sessionId);
            eventBus.post(new SessionChangedEvent(sessionId));
        }
    }
}
